package com.szq.netty.client;

import com.szq.netty.codec.RpcDecoder;
import com.szq.netty.codec.RpcEncoder;
import com.szq.netty.msg.Request;
import com.szq.netty.msg.Response;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @ClassName: ClientSocket
 * @Description:
 * @Author: szq
 * @Date: 2021-11-17 09:46:07
 */
public class ClientSocket implements Runnable{

    private ChannelFuture future;

    @Override
    public void run() {
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try{
            Bootstrap b = new Bootstrap();
            b.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.AUTO_READ, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(
                                    new RpcDecoder(Response.class),
                                    new RpcEncoder(Request.class),
                                    new MyClientHandler()
                                    );
                        }
                    });
            ChannelFuture f = b.connect("192.168.30.32", 7397).sync();
            this.future = f;
            f.channel().closeFuture().sync();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            workGroup.shutdownGracefully();
        }
    }

    public ChannelFuture getFuture() {
        return future;
    }

    public void setFuture(ChannelFuture future) {
        this.future = future;
    }
}
